package org.luosl.webmagicx

import java.io.File

import org.apache.commons.io.FileUtils
import org.luosl.webmagicx.utils.Logging
import org.luosl.webmagicx.cli.Cli
import org.luosl.webmagicx.conf.ConfLoader

import scalaj.http._

object Client extends Logging{

  def main(args: Array[String]): Unit = {

    val cli:Cli = Cli(args:_*)
    val cmd:Option[String] = cli.cliArgs.headOption
    val host:String = cli.optionValOrDefault("host","127.0.0.1")
    val port:Int = cli.optionValOrDefault("port","9000").toInt
    cmd match {
      case Some("submit") => submit(cli.optionVal("confPath"), host, port)
      case Some("kill") => kill(cli.optionVal("spiderId"), host, port)
      case Some("overview") => overview(host, port)
      case Some("shutdown") => shutdown(host, port)
      case _ =>
        logWarning("请输入有效的命令: submit、kill、overview、shutdown")
    }

  }

  /**
    * 提交一个任务
    * @param path 配置文件或目录
    * @param host host
    * @param port port
    */
  def submit(path:String, host:String, port:Int): Unit ={
    val cfs:Array[File] = ConfLoader.listConfFile(path, suffix = "spider.xml")
    val fileAndXmls:Array[(File, String)] = cfs.map(f=> f->FileUtils.readFileToString(f, "UTF-8"))
    fileAndXmls.foldLeft(1){ (count, tu)=>
      val (file,xml):(File, String) = (tu._1, tu._2)
      println(s"正在提交:${file.getAbsolutePath};当前进度:$count / ${fileAndXmls.length}")
      val resp:String = Http(s"http://$host:$port/spider/submit")
        .postData(xml.getBytes("UTF-8"))
        .asString.body
      println(resp)
      count + 1
    }
  }

  /**
    * 停止一个任务
    * @param id 爬虫id
    * @param host host
    * @param port port
    */
  def kill(id:String, host:String, port:Int): Unit ={
    println(Http(s"http://$host:$port/spider/kill/$id").asString.body)
  }

  /**
    * 启动一个爬虫
    * @param id 爬虫id
    * @param host host
    * @param port port
    */
  def start(id:String, host:String, port:Int): Unit ={
    println(Http(s"http://$host:$port/spider/start/$id").asString.body)
  }

  /**
    * 系统概览
    * @param host host
    * @param port port
    */
  def overview(host:String, port:Int): Unit ={
    println(Http(s"http://$host:$port/system/overview").asString.body)
  }

  /**
    * 终止系统
    * @param host host
    * @param port port
    */
  def shutdown(host:String, port:Int): Unit ={
    println(Http(s"http://$host:$port/system/shutdown").asString.body)
  }

}
